<template>
  <div class="univer-container">
    <!-- <div class="table-title">{{ formTitle }}</div>
    <div class="formula-detail">
      <el-collapse v-model="activeNames" class="formula-collapse" accordion @change="handleChange">
        <el-collapse-item title="公式详情" name="1">
          <div class="formula">
            填表范围: 考核后发生容量电费扣减的省内公用煤电机组 (不含应急备用、跨省跨区煤电机组)
          </div>
        </el-collapse-item>
      </el-collapse>
    </div> -->
    <div v-if="dynamicId" :id="dynamicId" class="demo-page-wrapper"></div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'DynamicForm',
  inheritAttrs: false,
});

import { CoalDeductionInfo } from '@/utils/formData';
import { integerRule, numberDecimal2, requireRule, validate } from '@/utils/pattern';
import { setupUniver } from '@/utils/setup-univer';
import FormAPI from '@/api/batch/form.api';
import FormDataAPI from '@/api/batch/formData.api';

const props = defineProps<{
  readonly?: boolean;
  formId?: string;
  recordId?: string;
  id?: string; // 表单数据对应记录id
  // formData?: any; // 表单数据
  // jsonSchema?: any; // 表单jsonSchema
  batchInfo?: any; // 批次信息
}>();
const dynamicId = ref('');
const formTitle = ref<string>('煤电机组容量电费扣减情况');
const tableData = ref<CoalDeductionInfo[]>([]);
let tempInitData: any = {}; // 表单模板
let univerAPIInstance: any = null; // univer api实例
let univerInstance: any = null; // univer 电子表格实例

const patternMap: any = {
  single_capacity: numberDecimal2,
  declared_val: numberDecimal2,
  capacity_charge: numberDecimal2,
  standard_fall_num: integerRule,
  name: requireRule,
  no: requireRule,
  reason_deduction: requireRule,
};

// 获取表单json和formData
const getAllValue = async () => {
  const fWorkbook = univerAPIInstance.getActiveWorkbook();
  const fWorksheet = fWorkbook.getActiveSheet();
  await fWorkbook.endEditingAsync(true);

  const { formElements = [] } = tempInitData;
  let maxMap: any = {};
  let datasMap: any = {};
  let rows: any = [];

  console.log('formElements-', formElements);
  if (formElements) {
    for (let i = 0; i < formElements.length; i++) {
      const item = formElements[i];
      const arr = item.position.split(',');

      // 起始行 终止列 终止行 终止列(index)需要+1
      // let fRange = fWorksheet.getRange(
      //   Number(arr[0]),
      //   Number(arr[1]),
      //   Number(arr[2]),
      //   Number(arr[3]) + 1
      // );
      const pos = positionToRange(item.position);
      let fRange = fWorksheet.getRange(pos);
      let cdatas = fRange.getCellDatas();
      datasMap[item.code] = cdatas;
      maxMap[item.code] = (arr[2] - arr[0] + 1) * (arr[3] - arr[1] + 1);
    }
    const maxLen = Math.max.apply(Math, Object.values(maxMap));
    console.log('maxMap-', maxLen, datasMap);

    // 获取formData i-行数
    for (let i = 0; i < maxLen; i++) {
      rows.push({});
      Object.keys(maxMap).forEach((key) => {
        if (!datasMap[key][i]) {
          rows[i][key] = '';
        } else {
          rows[i][key] = datasMap[key][i][0]?.v ?? '';
        }
      });
    }
    console.log('rows-', rows);
  }

  // 获取活动工作簿
  const jsonData = fWorkbook.save();
  console.log('jsonData-', jsonData);

  const obj: any = {
    jsonSchema: jsonData,
  };
  if (rows && rows.length > 0) {
    obj.formData = {};
    obj.formData.data = rows;
  }
  return obj;
};

function positionToRange(position: string) {
  const [startRow, startColumn, endRow, endColumn] = position.split(',');
  function getExcelColumn(number: number | string) {
    if (typeof number !== 'number') {
      number = parseInt(number);
    }
    let column = '';
    while (number >= 0) {
      const remainder = number % 26;
      column = String.fromCharCode(remainder + 65) + column;
      number = Math.floor(number / 26) - 1;
      if (number < 0) break;
    }
    return column;
  }
  return `${getExcelColumn(startColumn)}${parseInt(startRow) + 1}:${getExcelColumn(endColumn)}${
    parseInt(endRow) + 1
  }`;
}

const allApi = () => {
  // 获取指定坐标单元格
  const fWorkbook = univerAPIInstance.getActiveWorkbook();
  const fWorksheet = fWorkbook.getActiveSheet();
  const fRange = fWorksheet.getRange(1, 0, 4, 15); // 起始行 终止列 终止行 终止列(index)需要+1
  // console.log('getRange1-', fWorksheet.getRange(0, 0)); // 指定0行0列
  // console.log('getRange2-', fWorksheet.getRange(0, 1, 10, 15)); // 从第0行第1列开始，到第10行第15列结束
  // console.log('getRange3-', fWorksheet.getRange('H6')); // 指定H6单元格
  // console.log('getRange4-', fWorksheet.getRange('H6', 'J10'));
  console.log('getCellData-', fRange.getCellDatas());
  // console.log('getCell-', fWorksheet.getRange('H6').getCell());

  // 用户监听输入结束事件
  univerAPIInstance.addEvent(univerAPIInstance.Event.SheetEditEnded, (params: any) => {
    console.log('用户输入结束事件', params);
  });

  // 单元格点击事件
  univerAPIInstance.addEvent(univerAPIInstance.Event.CellClicked, (params: any) => {
    const { worksheet, row, column } = params;
    console.log('点击的单元格:', worksheet.getRange(row, column).getA1Notation());
  });
  // 用户输入结束事件
  // univerAPIInstance.getSheetHooks().onAfterCellEdit((params) => {
  //   console.log('用户输入结束事件2', params);
  // });
  // 范围框选事件
  fWorkbook.onSelectionChange((selections: any) => {
    console.log('Selection changed:', selections);
  });
  // 单元格内容改变事件
  // fWorkbook.onCellChange((cell) => {
  //   console.log('Cell changed:', cell);
  // });
};

// 查询表单定义模板数据
const getTemplateData = () => {
  return new Promise((resolve, reject) => {
    FormAPI.getDefinitionDetail(props.formId as any)
      .then((data: any) => {
        const { formName = '', schemaJson } = data;
        formTitle.value = formName;
        resolve(schemaJson);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

const refreshData = () => {
  return new Promise((resolve, reject) => {
    FormDataAPI.getFormDataById(props.id as any)
      .then((data: any) => {
        resolve(data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

defineExpose({
  setValue() {},
  async getValue() {
    return getAllValue();
  },
  validate: () => validate(tableData.value, patternMap),
});
function initPermission() {
  const permission = univerAPIInstance.getPermission();
  const permissionArr = [
    permission.permissionPointsDefinition.WorkbookCreateSheetPermission, // 创建工作簿
    permission.permissionPointsDefinition.WorkbookDeleteSheetPermission, // 删除工作簿
    permission.permissionPointsDefinition.WorkbookRenameSheetPermission, // 重命名工作簿
    permission.permissionPointsDefinition.WorkbookMoveSheetPermission, // 移动工作簿
    permission.permissionPointsDefinition.WorksheetDeleteColumnPermission, // 删除列
    permission.permissionPointsDefinition.WorksheetDeleteRowPermission, // 删除行
    permission.permissionPointsDefinition.WorksheetInsertColumnPermission, // 插入列
    permission.permissionPointsDefinition.WorksheetDeleteRowPermission, // 插入行
    permission.permissionPointsDefinition.WorksheetInsertRowPermission, // 插入行
    permission.permissionPointsDefinition.WorksheetSetCellStylePermission, // 设置单元格样式
    permission.permissionPointsDefinition.WorksheetSetColumnStylePermission, // 设置列样式
    permission.permissionPointsDefinition.WorksheetSetRowStylePermission, // 设置行样式
  ];

  // unitId 是工作簿的 id, WorkbookEditablePermission 是权限点位, false 表示该权限不可使用
  if (props.readonly) {
    const workbookEditablePermission =
      permission.permissionPointsDefinition.WorkbookEditablePermission;
    permission.setWorkbookPermissionPoint(
      univerAPIInstance.getActiveWorkbook().id,
      workbookEditablePermission,
      false
    );
  }
  const unitId = univerAPIInstance.getActiveWorkbook().id;
  permissionArr.forEach((item) => {
    permission.setWorkbookPermissionPoint(unitId, item, false);
  });
}
onMounted(async () => {
  console.log(`prop-${props.formId}-${props.id || 'undefined'}`);

  dynamicId.value = `wrapper${props.formId}`;
  const schemaJson: any = await getTemplateData();
  tempInitData = JSON.parse(schemaJson || '{}');

  let initData: any = {}; // 表单数据

  if (!props.id) {
    // 表单定义渲染模板
    console.log(`first-${props.formId}`);
    initData = tempInitData?.univerContent;
  } else {
    // 第二次进来(有过保存的历史数据)
    const curData: any = await refreshData();
    console.log(`second-${props.id}`, curData);
    if (curData.jsonSchema && '{}' !== curData.jsonSchema) {
      initData = JSON.parse(curData.jsonSchema);
    } else {
      initData = tempInitData?.univerContent;
    }
  }
  console.log(`init-${props.id}`, initData);

  const { univerAPI, univer } = setupUniver(dynamicId.value, {
    data: initData, // 初始化数据
    header: false,
    footer: true,
    dataValidationConfig: {
      showEditOnDropdown: false,
    },
  });
  univerAPIInstance = univerAPI;
  univerInstance = univer;
  console.log('univer-', univerAPI, univer);

  initPermission();
});

// 销毁
onBeforeUnmount(() => {
  console.log('before-unmount');
  univerInstance?.dispose();
  univerAPIInstance?.dispose();
  univerInstance = null;
  univerAPIInstance = null;
});
</script>

<style lang="scss" scoped>
.formula-detail {
  display: flex;
  justify-content: flex-end;
}
.formula-collapse {
  max-width: 100%;
  border-radius: 10px;
  background-color: #ffffff;
  padding-left: 10px;

  :deep(.el-collapse-item__header) {
    color: #4080ff;
    background-color: transparent;
  }
}
.formula {
  padding: 5px;
}
.univer-container {
  height: 100%;
  padding: 0 0 0 5px;
}
.demo-page-wrapper {
  height: 100%;
}
</style>
